package com.zh.business.base.exception.handler;


import com.zh.business.base.exception.MsgException;
import com.zh.business.base.util.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 全局异常捕捉处理
 *
 * @author walle
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MsgException.class)
    @ResponseBody
    public JsonResult handleException(MsgException e) {
//		e.printStackTrace();
//        LOGGER.warn("catch exception:{}", e.getMessage());
        return JsonResult.fail(e.getMessage()).data(e.getMessage());
    }

    //捕获 未授权 UnauthorizedException 异常
    //@ExceptionHandler(UnauthorizedException.class)
    //@ResponseBody
    //public JsonResult unauthorizedException(UnauthorizedException e) {
    //    LOGGER.warn("catch exception:{}", e.getMessage());
    //    return JsonResult.fail("权限不足，无权操作！");
    //}

    //捕获 Jackson序列化解析 HttpMessageNotReadableException 异常
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public JsonResult HttpMessageNotReadableException(HttpMessageNotReadableException e) {
        LOGGER.error("catch exception:{}", e.getMessage());
        return JsonResult.fail("Jackson序列化解析错误").data(e.getMessage());
    }

    //捕获 @Valid 验证失败 MethodArgumentNotValidException 异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public JsonResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        LOGGER.error("catch exception:{}", e.getMessage());
        return JsonResult.fail(
                "对象名称：" + fieldError.getObjectName() + "->字段：" + fieldError.getField()
                        + "->" + fieldError.getDefaultMessage()
        ).data(e.getMessage());
    }

    //捕获Exception异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JsonResult exception(Exception e) {
        e.printStackTrace();
        //记录日志
        LOGGER.error("catch exception:{}", e.getMessage());
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String error = sw.toString();
        return JsonResult.fail("系统异常，请稍候重试。").data(error);
    }
}
